package com.funtonow.jqdk.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.bean.DkNumBean;
import com.funtonow.jqdk.bean.HkInfoBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.TencentSecretBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.fkcs.ui.DkFailActivity;
import com.funtonow.jqdk.fkcs.ui.DkSuccessActivity;
import com.funtonow.jqdk.fkcs.ui.FkMainActivity;
import com.funtonow.jqdk.service.CountDownBroadcastReceiver;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.widget.ProgressDialogUtil;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.ED_JS;
import static com.funtonow.jqdk.base.UrlUtils.GET_COS_KEY;
import static com.funtonow.jqdk.base.UrlUtils.HK_LIST;
import static com.funtonow.jqdk.base.UrlUtils.HOME_LIST;
import static com.funtonow.jqdk.base.UrlUtils.JH_RECORD;
import static com.funtonow.jqdk.base.UrlUtils.PV;
import static com.funtonow.jqdk.base.UrlUtils.TOKEN_LOGIN;

/**
 * @author Lenovo
 */
public class SplashActivity extends BaseActivity {


    @BindView(R.id.ll_sqj)
    LinearLayout llSqj;
    @BindView(R.id.ll_ssq)
    LinearLayout llSsq;

    private UserInfoBean userInfoBean;
    private CountDownBroadcastReceiver countDownBroadcastReceiver;
    private IntentFilter intentFilter;


    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        if (AppUtils.getAppName(this).equals(getString(R.string.sqj_app_name))) {
            Constants.OWN_APP_ID = Constants.SQJ_APP_ID;
            Constants.APP_ID = Constants.SQJ_WX_APP_ID;
            Constants.AI_APP_KEY = Constants.SQJ_AI_APP_KEY;
            Constants.AI_SECRET_KEY = Constants.SQJ_AI_SECRET_KEY;
            Constants.XYS_HTML = Constants.SQJ_XYS_HTML;
            Constants.CNS_HTML = Constants.SQJ_CNS_HTML;
            Constants.YSS_HTML = Constants.SQJ_YSS_HTML;
            Constants.VIP_HTML = Constants.SQJ_VIP_HTML;
            initToolbar(getResources().getString(R.string.sqj_loan_title));
            llSqj.setVisibility(View.VISIBLE);
            llSsq.setVisibility(View.GONE);
            mIbReturn.setVisibility(View.INVISIBLE);
        } else if (AppUtils.getAppName(this).equals(getString(R.string.ssq_app_name))) {
            Constants.OWN_APP_ID = Constants.SSQ_APP_ID;
            Constants.APP_ID = Constants.SSQ_WX_APP_ID;
            Constants.AI_APP_KEY = Constants.SSQ_AI_APP_KEY;
            Constants.AI_SECRET_KEY = Constants.SSQ_AI_SECRET_KEY;
            Constants.XYS_HTML = Constants.SSQ_XYS_HTML;
            Constants.CNS_HTML = Constants.SSQ_CNS_HTML;
            Constants.YSS_HTML = Constants.SSQ_YSS_HTML;
            Constants.VIP_HTML = Constants.SSQ_VIP_HTML;
            llSqj.setVisibility(View.GONE);
            llSsq.setVisibility(View.VISIBLE);
        } else {
            Constants.OWN_APP_ID = Constants.YQS_APP_ID;
            Constants.APP_ID = Constants.YQS_WX_APP_ID;
            Constants.AI_APP_KEY = Constants.YQS_AI_APP_KEY;
            Constants.AI_SECRET_KEY = Constants.YQS_AI_SECRET_KEY;
            Constants.XYS_HTML = Constants.YQS_XYS_HTML;
            Constants.CNS_HTML = Constants.YQS_CNS_HTML;
            Constants.YSS_HTML = Constants.YQS_YSS_HTML;
            Constants.VIP_HTML = Constants.YQS_VIP_HTML;
            initToolbar(getResources().getString(R.string.yqs_loan_title));
            llSqj.setVisibility(View.VISIBLE);
            llSsq.setVisibility(View.GONE);
            mIbReturn.setVisibility(View.INVISIBLE);
        }
        intoAppTj();
        userInfoBean = SPUtil.getUserInfo();
        if (SPUtil.getUserInfo() != null) {
            tokenLogin(userInfoBean.getToken());
        }
        countDownBroadcastReceiver = new CountDownBroadcastReceiver();
        intentFilter = new IntentFilter();
        //这里定义接受器监听广播的类型，这里添加相应的广播
        intentFilter.addAction("countdown.receiver");
        //实例化接收器
        //注册事件，将监听类型赋给对应的广播接收器----所以这叫动态注册
        registerReceiver(countDownBroadcastReceiver, intentFilter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(countDownBroadcastReceiver);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.activity_aplash;
    }


    public void intoAppTj() {
        String httpUrl = PV + "appid=" + Constants.OWN_APP_ID + "&channel=" + AppUtils.getAppMetaData(this, "UMENG_CHANNEL");
        if (userInfoBean != null) {
            httpUrl += "&openid=" + userInfoBean.getOpenid();
        } else {
            httpUrl += "&openid=" + SPUtil.getUUID();
        }
        HttpUtil.getInstance().getDataAsynFromNet(httpUrl, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                getCosKey();

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void tokenLogin(String token) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", Constants.OWN_APP_ID);
        params.put("token", token);
        params.put("shebei", String.format("Android %s%s%s", Build.VERSION.RELEASE, PhoneUtils.getDeviceBrand(), PhoneUtils.getSystemModel()));
        params.put("channel", AppUtils.getAppMetaData(this, "UMENG_CHANNEL"));
        params.put("system", String.valueOf(Build.VERSION.SDK_INT));
        params.put("viewuuid", SPUtil.getUUID());
        HttpUtil.getInstance().postDataAsynToNet(TOKEN_LOGIN, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " **********  ");
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum < 0) {
                    SPUtil.clear(SplashActivity.this);
                    Toast.makeText(SplashActivity.this, "token过期", Toast.LENGTH_SHORT).show();
                } else {
                    if (!AppUtils.getAppName(SplashActivity.this).equals(getString(R.string.ssq_app_name))) {
                        if (TimeUtils.isShowDialog()) {
                            Intent intent = new Intent("countdown.receiver");
                            intent.putExtra("msg", "广播");
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                                intent.setComponent(new ComponentName(getPackageName(), "com.funtonow.jqdk.service.CountDownBroadcastReceiver"));
                            }
                            sendBroadcast(intent);
                        }
                    }
                    SPUtil.put("userInfo", baseBean.user);
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void getCosKey() {
        Map<String, String> params = new HashMap<>();
        params.put("bucket", Constants.bucket);
        params.put("region", Constants.region);
        HttpUtil.getInstance().postDataAsynToNet(GET_COS_KEY, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") == 0) {
                    SqjAppliaction.tencentSecretBean = JSON.parseObject(jsonObject.getJSONObject("data").toJSONString(),
                            TencentSecretBean.class);
//                    if (!AppUtils.getAppName(SplashActivity.this).equals(getString(R.string.ssq_app_name))) {
//                        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
//                        finish();
//                    } else {
                    getLoanList();
//                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void getLoanList() {
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.OWN_APP_ID);
        param.put("app", "1");
        HttpUtil.getInstance().postDataAsynToNet(HOME_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + "  ************* ");
                ProgressDialogUtil.stopProgressDialog();
                SqjAppliaction.loanInfoBean = JSON.parseObject(jsonString, LoanInfoBean.class);
                if (SPUtil.getUserInfo() == null) {
                    startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                    finish();
                } else if (AppUtils.getAppName(SplashActivity.this).equals(getResources().getString(R.string.ssq_app_name))) {
                    getMoneyNum();
                } else {
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    /**
     * 得到可贷款金额
     */
    private void getMoneyNum() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(ED_JS, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " *********  ");
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum == -2) {
                    startActivity(new Intent(SplashActivity.this, FkMainActivity.class));
                } else if (baseBean.errnum == 0) {
                    DkNumBean dkNumBean = JSON.parseObject(baseBean.data, DkNumBean.class);
                    switch (dkNumBean.getState()) {
                        case 1:
                        case 2:
                            Intent intent = new Intent(SplashActivity.this, DkSuccessActivity.class);
                            intent.putExtra("dkInfo", baseBean.data);
                            startActivity(intent);
                            break;
                        default:
                            startActivity(new Intent(SplashActivity.this, MainActivity.class));
                            break;
                    }
                }
                finish();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
